package com.letv.whatslive.mongo.dao;


import com.google.common.collect.Lists;
import com.letv.whatslive.common.utils.DateUtils;
import com.letv.whatslive.common.utils.ObjectUtils;
import com.letv.whatslive.model.BusinessCooperation;
import com.letv.whatslive.model.Employee;
import com.letv.whatslive.model.convert.BusinessCooperationConvert;
import com.letv.whatslive.model.convert.EmployeeConvert;
import com.letv.whatslive.model.utils.ObjUtils;
import com.letv.whatslive.mongo.BaseDAO;
import com.letv.whatslive.redis.JedisDAO;
import com.mongodb.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 用户collection操作DAO
 * Created by shenyue on 16-3-2.
 */
@Repository
public class BusinessCooperationDao extends BaseDAO {

    private final static Logger logger = LoggerFactory.getLogger(BusinessCooperationDao.class);

    protected String collectionName = "businessCooperation";

    @Autowired
    protected JedisDAO jedisDAO;

    @Override
    protected void init() {
        super.init(this.collectionName);
    }

    @Override
    protected long getAutoIncrementId() {
        return idGenerate.generateId(this.collectionName);
    }

    public int saveOrUpdateBusinessCooperation(BusinessCooperation businessCooperation,Integer... saveType) {
        WriteResult result = null;
        if(businessCooperation!=null && businessCooperation.getId()!=null){
            DBObject query = new BasicDBObject("_id", businessCooperation.getId());
            DBObject dbo = this.dbCollection.findOne(query);
            if (dbo == null) {//insert
                dbo = BusinessCooperationConvert.castBusinessCooperationToDBObject(businessCooperation);
                if (dbo != null) {
                    result = this.dbCollection.save(dbo);
                }
            } else {//update
                DBObject update = new BasicDBObject();
                update=BusinessCooperationConvert.castBusinessCooperationToDBObject(businessCooperation);
                update.put("updateTime", System.currentTimeMillis());
                result = this.dbCollection.update(query, new BasicDBObject("$set", update), true, false);
            }
        }else{
            return ObjectUtils.toInteger(this.insert(BusinessCooperationConvert.castBusinessCooperationToDBObject(businessCooperation)));
        }
        return result.getN();

    }

    /**
     * 查询用户列表
     *
     * @param params 模糊查询的查询条件
     * @param orders 排序的条件
     * @param start  查询条件的开始分页数
     * @param limit  查询条件的分页每页条数
     * @return
     */
    public List<BusinessCooperation> getBusinessCooperationListByParams(Map<String, Object> params, Map<String, Object> orders, Integer start, Integer limit) {

        List<BusinessCooperation> result = Lists.newArrayList();
        if (limit == null) {
            limit = DEFAULT_NUM;
        }
        //TODO 临时用于检查错误用户数据
        BusinessCooperation errorBusinessCooperation = new BusinessCooperation();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject order = getOrderParams(orders);
            BasicDBObject query = getBasicDBObjectByParams(params);
            Integer skip = start == null ? 0 : start;
            DBCursor cur = this.dbCollection.find(query).skip(skip).sort(order).limit(limit);//按createTime的值倒叙排列
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                BusinessCooperation businessCooperation = BusinessCooperationConvert.castDBObjectToBusinessCooperation(dbObject);
                errorBusinessCooperation = businessCooperation;
                setValueToBusinessCooperation(businessCooperation);
                result.add(businessCooperation);
            }
        } catch (Exception e) {
            logger.error("uid:<"+errorBusinessCooperation.getId()+"> error:<"+e.getMessage()+">",e);
        }
        return result;
    }

    public List<BusinessCooperation> getAllBusinessCooperationByParams(Map<String, Object> params){
        List<BusinessCooperation> result = Lists.newArrayList();
        try {
            //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
            BasicDBObject query = getBasicDBObjectByParams(params);
            DBCursor cur = this.dbCollection.find(query);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                BusinessCooperation businessCooperation = BusinessCooperationConvert.castDBObjectToBusinessCooperation(dbObject);
                setValueToBusinessCooperation(businessCooperation);
                result.add(businessCooperation);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 根据主键查询一个用户
     * @param uid 用户主键
     * @return 一个BusinessCooperation对象
     */
    public BusinessCooperation getBusinessCooperationById(Long uid) {
        BasicDBObject query = new BasicDBObject();
        BusinessCooperation businessCooperation = new BusinessCooperation();
        query.put("_id", uid);
        DBObject dbObject = this.dbCollection.findOne(query);
        if (dbObject == null) return null;
        try {
            businessCooperation = BusinessCooperationConvert.castDBObjectToBusinessCooperation(dbObject);
            setValueToBusinessCooperation(businessCooperation);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return businessCooperation;
    }


    /**
     * 查询用户的数量
     * @param params 查询条件参数
     * @return 满足条件的文档记录数
     */
    public Long countBusinessCooperationByParams(Map params) {
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = getBasicDBObjectByParams(params);
        return this.dbCollection.count(query);
    }

    /**
     * 保存用户信息
     * @param businessCooperation
     * @return
     */
    public BusinessCooperation saveBusinessCooperation(BusinessCooperation businessCooperation) {
        try {
            businessCooperation.setId(getAutoIncrementId());
            DBObject dbo = BusinessCooperationConvert.castBusinessCooperationToDBObject(businessCooperation);
            WriteResult wr = this.dbCollection.insert(dbo);
            setValueToBusinessCooperation(businessCooperation);
            return businessCooperation;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 更新用户基本信息
     * @param businessCooperation
     */
    public void updateBusinessCooperation(BusinessCooperation businessCooperation) {
        DBObject queryCondition = new BasicDBObject();
        Long businessCooperationId = businessCooperation.getId();
        queryCondition.put("_id", businessCooperationId); // 用来确定要修改的文档
        DBObject setValue = BusinessCooperationConvert.castBusinessCooperationToDBObject(businessCooperation);
        //剔除主键修改
        if (setValue.containsKey("_id")) {
            setValue.removeField("_id");
        }
        DBObject values = new BasicDBObject("$set", setValue);
        this.dbCollection.update(queryCondition, values, false, false);
    }

    /**
     * 根据用户ID删除用户
     * @param uid
     */
    public void deleteBusinessCooperation(Long uid){
        BasicDBObject query = new BasicDBObject();
        query.put("_id", uid);
        this.dbCollection.remove(query);
    }

    /**
     * 获取排序的BasicDBObject对象
     * @param orders
     * @return
     */
    private BasicDBObject getOrderParams(Map<String, Object> orders) {
        BasicDBObject order = new BasicDBObject();
        if(null != orders &&orders.size()>0){
            for(String key : orders.keySet()){
                order.append(key, Integer.valueOf(String.valueOf(orders.get(key))));
            }
        }else{
            //默认按照创建时间排序
            order.append("createTime", -1);
        }
        return order;
    }

    /**
     * 根据查询参数Map获取查询条件对象
     * @param params 查询参数Map
     * @return
     */
    private BasicDBObject getBasicDBObjectByParams(Map params){
        //dbObj 类似于 mysql 查询中的 where 关键字，可以添加各种搜索条件
        BasicDBObject query = new BasicDBObject();// 新建查询基类对象 dbo
        if (params != null && params.size() > 0) {
            if (params.get("companyName") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("companyName") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("companyName", pattern);
            }
            if (params.get("companyContacter") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("companyContacter") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("companyContacter", pattern);
            }
            if (params.get("ourContacterDepartment") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("ourContacterDepartment") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("ourContacterDepartment", pattern);
            }
            if (params.get("ourContacter") != null) {
                Pattern pattern = Pattern.compile("^.*" + params.get("ourContacter") + ".*$", Pattern.CASE_INSENSITIVE);
                query.put("ourContacter", pattern);
            }
            if (params.get("cooperationStatus") != null) {
                query.put("cooperationStatus", ObjectUtils.toInteger(params.get("cooperationStatus")));
            }

            if(params.get("startTime_start") != null && params.get("startTime_end") != null){
                query.put("startTime", new BasicDBObject("$gt",
                        ObjectUtils.toLong(params.get("startTime_start"))).append("$lte", ObjectUtils.toLong(params.get("startTime_end"))));

            }
            if(params.get("createByPersonLoginNameIn")!=null){
                List<String> names= (List<String>) params.get("createByPersonLoginNameIn");
                if(names.size()>0){
                    BasicDBList values = new BasicDBList();
                    for(String name:names){
                        values.add(ObjectUtils.toString(name));
                    }
                    query.put("createByPersonLoginName", new BasicDBObject("$in", values));
                }
            }

		}
        return query;
    }


    private void setValueToBusinessCooperation(BusinessCooperation businessCooperation) {
        businessCooperation.setCreateTimeStr(businessCooperation.getCreateTime() != null ?
                DateUtils.long2YMDHMS(businessCooperation.getCreateTime()) : "");
        businessCooperation.setStartTimeStr(businessCooperation.getStartTime() != null ?
                DateUtils.long2YMDHMS(businessCooperation.getStartTime()) : "");
        businessCooperation.setEndTimeStr(businessCooperation.getEndTime() != null ?
                DateUtils.long2YMDHMS(businessCooperation.getEndTime()) : "");
        if(businessCooperation.getEndTime()!=null && businessCooperation.getEndTime()==4102416000000L){
            businessCooperation.setEndTimeIsForever(1);
        }else{
            businessCooperation.setEndTimeIsForever(2);
        }

    }
    /**
     * 根据用户ID列表获取用户列表
     * @param ids
     * @return
     */
    public List<BusinessCooperation> getBusinessCooperationListByIds(String ids) {

        List<BusinessCooperation> result = Lists.newArrayList();

        try {

            BasicDBList values = new BasicDBList();
            String[] idList = ids.split(",");
            for (String id : idList) {
                values.add(ObjectUtils.toLong(id));
            }

            BasicDBObject queryCondition = new BasicDBObject();
            queryCondition.put("_id", new BasicDBObject("$in", values));
            DBCursor cur = this.dbCollection.find(queryCondition);
            while (cur.hasNext()) {

                DBObject dbObject = cur.next();
                BusinessCooperation businessCooperation = BusinessCooperationConvert.castDBObjectToBusinessCooperation(dbObject);
                setValueToBusinessCooperation(businessCooperation);
                result.add(businessCooperation);
            }
        } catch (Exception e) {

            logger.error("getBusinessCooperationListByIds error ids===" + ids, e);
        }
        return result;
    }

    /**
     * 根据查询条件获取用户ID列表
     * @param params 查询条件
     * @param orders 排序条件
     * @return
     */
    public List<Long> getBusinessCooperationIdsByParams(Map<String, Object> params, Map<String, Object> orders) {

        List<Long> result = Lists.newArrayList();

        try {

            BasicDBObject query = getBasicDBObjectByParams(params);
            BasicDBObject order = getOrderParams(orders);
            DBCursor cur = this.dbCollection.find(query).sort(order);
            while (cur.hasNext()) {
                DBObject dbObject = cur.next();
                result.add(ObjUtils.toLong(dbObject.get("_id")));
            }
        } catch (Exception e) {

            logger.error("getBusinessCooperationIdsByParams error", e);
        }

        return result;
    }

}

